package org.vsg.security.model.persistence.hibernate.proc;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.vsg.common.pagination.datatrans.DataTransformer;
import org.vsg.common.pagination.keyword.PaginationKeyword;
import org.vsg.common.pagination.processor.AbstractPaginationProcessorHibernateDaoSupport;
import org.vsg.common.pagination.processor.PaginationProcessorException;
import org.vsg.common.pagination.processor.hibernate.HibernatePaginationQuery;
import org.vsg.common.pagination.sort.SortField;
import org.vsg.security.model.domain.SysRole;


/**
 * @author Bill Vison
 *
 */
public class SysRoleHierarchyPaginationProc extends AbstractPaginationProcessorHibernateDaoSupport {

	private static final Logger logger = LoggerFactory.getLogger(SysRoleHierarchyPaginationProc.class);	


	private Object[] getQueryCondition(String name) {
		
		Object[] condiction = new Object[2];
		
		Collection paramColl = new Vector();
		StringBuffer queryCondition = new StringBuffer();
		

		// set the object for array 
		condiction[0] = queryCondition;
		condiction[1] = paramColl;
		
		queryCondition.append("sysRole.flagDeleted = 0 ");
		
		if (name != null && !name.equals("")) {
			queryCondition.append("and sysRole.name like ? ");
			paramColl.add("%" + name + "%");
		}
		
		
		return condiction;
		
	}


	/* (non-Javadoc)
	 * @see org.vsg.commons.util.pagination.processor.PaginationProcessor#getPaginationList(org.vsg.commons.util.pagination.datatrans.DataTransformer)
	 */
	public List getPaginationList(DataTransformer transformer)
			throws PaginationProcessorException {
		// TODO Auto-generated method stub
		List dataList = new Vector();

		int offset = (Integer)transformer.getImplicitValue(PaginationKeyword.TFS_DATA_OFFSET);
		int rows = (Integer)transformer.getImplicitValue(PaginationKeyword.TFS_ROWS);

		Collection sortFields = (Collection)transformer.getImplicitValue(PaginationKeyword.TFS_SORTBY);

		// receive parameter name
		String name = (String)transformer.getValue("name");
		
		
		StringBuffer query = new StringBuffer("select ");
		query.append("sysRole ");
		query.append("from ").append(SysRole.class.getName());
		query.append(" as sysRole ");
		query.append("join sysRole.dependenceRoles as depRole ");
		
		// -------------- get the condition for the query 
		Object[] condition = getQueryCondition(name);

		StringBuffer queryCondition = (StringBuffer)condition[0];
		Collection paramColl = (Collection)condition[1];

		if (queryCondition.length() > 0) {
			query.append("where ");
			query.append(queryCondition);
		}
		// -----------------------------------------------
		query.append("group by depRole.id ");

		
		
		if (sortFields != null) {

			if (sortFields.size() > 0) {
				query.append("ORDER BY ");
				SortField sortField = null;
				for (Iterator iter = sortFields.iterator() ; iter.hasNext();) {
					sortField = (SortField)iter.next();						
					if (sortField.getField().equalsIgnoreCase("name")) {
						query.append("sysRole.name "+sortField.getSortOrder()+" ");
					}
					if (sortField.getField().equalsIgnoreCase("code")) {
						query.append("sysRole.code "+sortField.getSortOrder()+" ");
					}
				}
			}			
			// set default sort for these data
			else {
				query.append("ORDER BY sysRole.id desc ");
			}		}

		if (logger.isInfoEnabled()) {
			logger.info("Execute SQL :"+query.toString());
		}				

		HibernatePaginationQuery hibernateQuery = new HibernatePaginationQuery();
		hibernateQuery.setQuery(query.toString());
		hibernateQuery.setParams(paramColl.toArray());
		hibernateQuery.setStartIndex(offset);
		hibernateQuery.setRows(rows);
		
		HibernateTemplate template = this.getTemplate();
		
		
		List objList = (List)template.executeFind(hibernateQuery);
		Iterator dataIter = objList.iterator();			
		SysRole entity = null;
		while (dataIter.hasNext()) {
			entity = (SysRole)dataIter.next();
			dataList.add( entity );				
		}
		
		return dataList;
	}

	/* (non-Javadoc)
	 * @see org.vsg.commons.util.pagination.processor.PaginationProcessor#getTotalRecords(org.vsg.commons.util.pagination.datatrans.DataTransformer)
	 */
	public int getTotalRecords(DataTransformer transformer)
			throws PaginationProcessorException {
		// TODO Auto-generated method stub
		int totalRecord = 0;

		// receive parameter name
		String name = (String)transformer.getValue("name");
		
		
		StringBuffer query = new StringBuffer("SELECT ");
		query.append("count(*) ");
		query.append("from ").append(SysRole.class.getName());
		query.append(" as sysRole ");
		query.append("join sysRole.dependenceRoles as depRole ");
		// -------------- get the condition for the query 
		Object[] condition = getQueryCondition(name);

		StringBuffer queryCondition = (StringBuffer)condition[0];
		Collection paramColl = (Collection)condition[1];

		if (queryCondition.length() > 0) {
			query.append("where ");
			query.append(queryCondition);
		}
		// -----------------------------------------------		
		query.append("group by depRole.id ");

		
		if (logger.isInfoEnabled()) {
			logger.info("Execute SQL :"+query.toString());
		}
		
		HibernateTemplate template = this.getTemplate();
		Iterator iter = template.iterate(query.toString(),paramColl.toArray());			
		while (iter.hasNext()) {
			totalRecord = new Integer(iter.next().toString());
		}
		
		return totalRecord;
	}

}